<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
      <el-form-item label="客户名称" prop="CompanyName">
        <el-input v-model="queryParams.CompanyName"
                  placeholder="请输入客户名称"
                  clearable
                  style="width: 240px"
                  @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <!--<el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
      </el-col>-->
      <right-toolbar @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading"
              :data="customerList"
              row-key="ID"
              @expand-change="handleExpandChange"
              @selection-change="handleSelectionChange">
      <el-table-column type="expand">
        <template #default="props">
          <div v-if="!props.row.HasChildren" class="admin-customer-order-expand">
            <div>暂无订单数据</div>
          </div>
          <div v-else class="admin-customer-order-expand select-table">
            <el-card shadow="never" header-class="recharge-card-header">
              <template #header>
                <span style="font-weight: bold">订单信息</span>
              </template>
              <el-table v-loading="props.row.loading" row-key="ID" :data="props.row.children">
                <el-table-column label="编号" prop="ID" width="80" />
                <el-table-column label="点卷(实充)" prop="PointRollAmount" width="200" />
                <el-table-column label="点卷(赠品)" prop="PointRollGiftAmount" width="200" />
                <el-table-column label="学习机(实充)" prop="PadAmount" />
                <el-table-column label="学习机(赠品)" prop="PadGiftAmount" />
                <el-table-column label="余额(点卷)" prop="PadGiftAmount" />
                <el-table-column label="学习机(点卷)" prop="PadGiftAmount" />
                <el-table-column label="充值时间" prop="Created">
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.Created) }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                  <template #default="scope">
                    <el-button type="warning" link icon="Edit" size="small" @click="handleUpdateProducePrice(scope.row)">调价</el-button>
                    <el-button type="danger" link icon="Delete" size="small" @click="handleUpdate(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" prop="ID" width="80" />
      <el-table-column label="代理商名称" prop="CompanyName" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="联系人" prop="Contacts" :show-overflow-tooltip="true" width="100" />
      <el-table-column label="联系方式" prop="UserName" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="代理商类型" prop="TypeName" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="代理商地址" prop="ProvinceId" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ scope.row.ProvinceName }}{{scope.row.CityName}}{{scope.row.AreaName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="详细地址" prop="AddressDetail" />
      <el-table-column label="状态" prop="Valid" width="80">
        <template #default="scope">
          <span>{{ scope.row.Valid ? '正常' : '停用' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="Created" width="100">
        <template #default="scope">
          <span>{{ parseTime(scope.row.Created) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="warning" icon="Edit" size="small" style="padding-left: 8px; padding-right: 8px" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button type="primary" icon="Coin" size="small" style="padding-left: 8px; padding-right: 8px" @click="handleRecharge(scope.row)">充值</el-button>
          <el-popconfirm v-if="scope.row.Valid" class="box-item" title="是否停用该账号" placement="top-start" @confirm="handleDisableCustomer(scope.row)">
            <template #reference>
              <el-button type="danger" icon="Lock" size="small" style="padding-left: 8px; padding-right: 8px">停用</el-button>
            </template>
          </el-popconfirm>
          <el-button v-else @click="handleOpenCustomer(scope.row)" type="success" icon="Unlock" size="small" style="padding-left: 8px; padding-right: 8px">启用</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改客户对话框 -->
    <el-dialog :title="title" v-model="open" width="1100px" header-class="card-header" :draggable="!!form.ID" destroy-on-close>
      <el-form ref="customerRef" :model="form" :rules="rules" size="large" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="代理商名称" prop="CompanyName">
              <el-input v-model="form.CompanyName" placeholder="请输入代理商名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="代理商类型" prop="ProxyTypeId">
              <el-select v-model="form.ProxyTypeId" placeholder="请选择代理商类型" style="width: 100%">
                <el-option v-for="item in listProxy" :key="item.ID" :label="item.TypeName" :value="item.ID" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="联系人" prop="Contacts">
              <el-input v-model="form.Contacts" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系方式" prop="UserName">
              <el-input v-model="form.UserName" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="代理商地址" required>
              <el-col :span="8">
                <el-form-item prop="ProvinceId" style="margin-right:5px;">
                  <el-select v-model="form.ProvinceId" @change="handleChangeProvince" placeholder="所在省份" style="width: 100%">
                    <el-option v-for="item in ProvinceList" :key="item.ID" :label="item.Name" :value="item.ID" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="CityId" style="margin-right:5px;">
                  <el-select v-model="form.CityId" @change="handleChangeCity" placeholder="所在市" style="width: 100%">
                    <el-option v-for="item in CityList" :key="item.ID" :label="item.Name" :value="item.ID" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="AreaId">
                  <el-select v-model="form.AreaId" placeholder="所在区" style="width: 100%">
                    <el-option v-for="item in AreaList" :key="item.ID" :label="item.Name" :value="item.ID" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-bottom: 10px">
          <el-col :span="20">
            <el-form-item label="详细地址" prop="AddressDetail">
              <el-input v-model="form.AddressDetail" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <OrderRecharge v-if="!form.ID" recharge-title="首充额度配置" v-model:recharge-data="RechargeData" v-model:product-data="ProductListData" />
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="账户信息" v-model="openShowAccount" width="800px" header-class="card-header" draggable destroy-on-close>
      <div>账户：{{addAccountBack.UserName}}</div>
      <div style="display:flex;align-items:center;">密码：{{addAccountBack.PassWord}}<el-icon @click="handleCopy" style="cursor:pointer;margin-left:5px"><DocumentCopy /></el-icon></div>
    </el-dialog>

    <!-- 充值对话框 -->
    <el-dialog title="充值点卷" v-model="visibleRecharge" width="800px" header-class="card-header" draggable destroy-on-close>
      <OrderRecharge v-model:recharge-data="RechargeData" v-model:product-data="ProductListData" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitRecharge">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改订单产品价格 -->
    <el-dialog title="充值点卷" v-model="visibleOrderProduct" width="800px" header-class="card-header" draggable destroy-on-close>
      <OrderRecharge v-model:recharge-data="RechargeData" v-model:product-data="ProductListData" :visible-recharge="false" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="updateRecharge">确 定</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Customer">
  import { useTemplateRef } from 'vue';
  import lodash from 'lodash';
  import { ElNotification } from 'element-plus';
  import useClipboard from '@/utils/hooks/clipboard';
  import * as customerApi from '@/api/customer';
  import { listAreas, listProduct } from '@/api/common';
  import { PageData } from '@/utils/common-api';
  import OrderRecharge from './components/order-recharge.vue';

  const { proxy } = getCurrentInstance()
  const { copyText } = useClipboard();

  const customerRef = useTemplateRef('customerRef');
  const loading = ref(true)
  const single = ref(true)
  const multiple = ref(true)
  const ids = ref([])
  const total = ref(0)
  const customerList = ref([])
  const title = ref('')
  const open = ref(false)
  const ProvinceList = ref([]);
  const CityList = ref([]);
  const AreaList = ref([]);
  const listProxy = ref([]);
  const ProductList = ref([]);
  const ProductListData = ref([]);
  const openShowAccount = ref(false);
  const addAccountBack = ref({});
  const visibleRecharge = ref(false);
  const ActiveCustomer = ref(null);
  const ActiveOrder = ref(null);
  const visibleOrderProduct = ref(false);

  const RechargeData = ref({
    PointRollAmount: null,
    PointRollGiftAmount: null,
    PadAmount: null,
    PadGiftAmount: null
  })

  const data = reactive({
    form: {},
    queryParams: {
      PageNum: 1,
      PageSize: 10,
      CompanyName: undefined
    },
    rules: {
      CompanyName: [{ required: true, message: "客户名称不能为空", trigger: "blur" }],
      DiscountRate: [{ required: true, message: "代理商折扣不能为空", trigger: "blur" }],
      Contacts: [{ required: true, message: "联系人不能为空", trigger: "blur" }],
      UserName: [{ required: true, message: "联系方式不能为空", trigger: "blur" }],
      ProvinceId: [{ required: true, message: "所属省份不能为空", trigger: "blur" }],
      CityId: [{ required: true, message: "所属市不能为空", trigger: "blur" }],
      AreaId: [{ required: true, message: "所属区不能为空", trigger: "blur" }],
      AddressDetail: [{ required: true, message: "详细地址不能为空", trigger: "blur" }],
    },
  })

  const { queryParams, form, rules } = toRefs(data)


  /** 查询客户列表 */
  function getList() {
    loading.value = true
    customerApi.listCustomer(queryParams.value).then(resp => {
      const { list, totle } = PageData(resp)
      total.value = totle;
      customerList.value = list;
      loading.value = false;
    })
  }
  /** 获取省份列表 */
  function getProvince() {
    listAreas().then(resp => {
      ProvinceList.value = resp || [];
    })
  }
  /** 获取代理商类型 */
  function getProxyType() {
    customerApi.listProxyType().then(resp => {
      listProxy.value = resp || [];
    })
  }
  
  /** 修改代理商信息 */
  function handleUpdate(rowData) {
    reset()
    form.value = rowData;
    title.value = "修改客户信息";
    CityList.value = [];
    AreaList.value = [];
    if (rowData.ProvinceId) {
      listAreas(rowData.ProvinceId).then(cities => {
        CityList.value = cities || [];
      })
    }
    if (rowData.CityId) {
      listAreas(rowData.CityId).then(areas => {
        AreaList.value = areas || [];
      })
    }
    open.value = true
  }
  /** 修改产品价格 */
  function handleUpdateProducePrice(row) {
    customerApi.GetOrderProduct(row.ID).then(list => {
      ActiveOrder.value = row;
      ProductListData.value = list.map(item => {
        return {
          ...item,
          Key: item.ID || Date.now(),
          Amount: item.RealPrice
        }
      });
      visibleOrderProduct.value = true;
    }).catch(() => {
      
    })
  }
  function handleDisableCustomer(rowData) {
    loading.value = true;
    customerApi.DisableCustomer(rowData.ID).then(() => {
      proxy.$modal.notifySuccess(`客户${rowData.CompanyName}已停用成功`);
      getList();
    }).finally(() => {
      loading.value = false;
    })
  }

  function handleOpenCustomer(rowData) {
    loading.value = true;
    customerApi.OpenCustomer(rowData.ID).then(() => {
      proxy.$modal.notifySuccess(`客户${rowData.CompanyName}已启用成功`);
      getList();
    }).finally(() => {
      loading.value = false;
    })
  }

  /** 点击充值按钮：打开充值对话框 */
  function handleRecharge(rowData) {
    RechargeData.value = {
      PointRollAmount: null,
      PointRollGiftAmount: null,
      PadAmount: null,
      PadGiftAmount: null
    };
    loading.value = true;
    customerApi.listPrevRechargeDetail(rowData.ID).then(list => {
      ActiveCustomer.value = rowData; 
      ProductListData.value = ProductList.value.map(item => {
        const prevItem = list.find(prev => prev.ProductId === item.ID);
        if (prevItem) {
          return {
            ...item,
            Trend: prevItem.Price > item.Price ? 'down' : prevItem.Price < item.Price ? 'up' : 'old',
            Amount: prevItem.RealPrice,
            ProductName: item.ProductName
          }
        }
        return { ...item, Trend: 'old' }
      })
      loading.value = false;
      visibleRecharge.value = true;
    }).catch(() => {
      ProductListData.value = lodash.cloneDeep(ProductList.value);
      loading.value = false;
      visibleRecharge.value = true;
    })
  }

  function handleQuery() {
    queryParams.value.PageNum = 1
    getList()
  }

  function resetQuery() {


  }
  /** 获取区级数据 */
  function handleChangeProvince(value) {
    form.value.CityId = null;
    form.value.AreaId = null;
    CityList.value = [];
    AreaList.value = [];
    listAreas(value).then(resp => {
      CityList.value = resp || [];
    })
  }
  /** 获取市级数据 */
  function handleChangeCity(value) {
    form.value.AreaId = null;
    AreaList.value = [];
    listAreas(value).then(resp => {
      AreaList.value = resp || [];
    })
  }
  /** 重置数据 */
  function reset() {
    if (customerRef.value) {
      customerRef.value.resetFields();
    }
    CityList.value = [];
    AreaList.value = [];
  }
  /** 添加客户信息(代理商) */
  function handleAdd() {
    reset();
    form.value = {};
    RechargeData.value = {
      PointRollAmount: null,
      PointRollGiftAmount: null,
      PadAmount: null,
      PadGiftAmount: null
    };
    ProductListData.value = lodash.cloneDeep(ProductList.value);
    open.value = true
    title.value = "添加客户"
  }

  function handleCopy() {
    const text = `账户：${addAccountBack.value.UserName}\n密码：${addAccountBack.value.PassWord}`;
    copyText(text);
    proxy.$modal.msg("复制成功！")
  }

  /** 提交按钮 */
  function submitForm() {
    if (customerRef.value) {
      customerRef.value.validate(valid => {
        if (valid) {
          if (form.value.ID != undefined) {
            customerApi.updateCustomer({
              ID: form.value.ID,
              CompanyName: form.value.CompanyName,
              UserName: form.value.UserName,
              Contacts: form.value.Contacts,
              ProvinceId: form.value.ProvinceId,
              CityId: form.value.CityId,
              AreaId: form.value.AreaId,
              AddressDetail: form.value.AddressDetail
            }).then(response => {
              proxy.$modal.msgSuccess("修改成功")
              open.value = false
              getList()
            })
          } else {

            customerApi.addCustomer({
              ...form.value,
              PointRollAmount: RechargeData.value.PointRollAmount || 0,
              PointRollGiftAmount: RechargeData.value.PointRollGiftAmount || 0,
              PadAmount: RechargeData.value.PadAmount || 0,
              PadGiftAmount: RechargeData.value.PadGiftAmount || 0,
              ProductPrice: JSON.stringify(ProductListData.value)
            }).then(response => {
              const result = lodash.get(response, '[0]', {});
              if (result.Status === 1) {
                proxy.$modal.msgSuccess("新增成功")
                addAccountBack.value = result;
                open.value = false;
                openShowAccount.value = true;
                getList()
              } else {
                // 接口请求状态有误，弹窗提示
                ElNotification.error({
                  title: '错误',
                  message: result.Msg,
                })
              }
            })
          }
        }
      })
    }
  }
  /** 提交充值 */
  function submitRecharge() {
    customerApi.AddRechargeOrder({
      ProxyId: ActiveCustomer.value.ID,
      RechargeData: JSON.stringify(RechargeData.value),
      ProductPrice: JSON.stringify(ProductListData.value)
    }).then((result) => {
      if (result[0].Status === 1) {
        proxy.$modal.notifySuccess("充值成功")
        visibleRecharge.value = false;
      } else {
        // 接口请求状态有误，弹窗提示
        ElNotification.error({
          title: '错误',
          message: '充值失败，参数有误',
        })
      }
    })
  }
  /** 调价 */
  function updateRecharge() {
    customerApi.UpdateOrderProduct({
      OrderId: ActiveOrder.value.ID,
      ProductPrice: JSON.stringify(ProductListData.value)
    }).then(() => {
      proxy.$modal.notifySuccess("调价成功");
    }).finally(() => {
      visibleOrderProduct.value = false;
    })
  }

  /** 取消按钮 */
  function cancel() {
    open.value = false;
    visibleRecharge.value = false;
    visibleOrderProduct.value = false;
    reset()
  }

  function handleExport() { }

  function handleExpandChange(row, expandedRows) {
    if (expandedRows.find(ele => ele == row)) {
      if (row.HasChildren && lodash.get(row, 'children.length', 0) === 0) {
        row.loading = true;
        customerApi.listOrder(row.ID).then(list => {
          row.children = list;
          row.loading = false;
        })
      }
    }
  }

  /** 多选框选中数据 */
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.customerId)
    single.value = selection.length != 1
    multiple.value = !selection.length
  }

  listProduct().then(list => {
    ProductList.value = list.map(item => ({ ...item, Amount: item.Price }));
  })
  getProvince();
  getProxyType();
  getList();

</script>
<style lang="scss">
  .card-header {
    border-bottom: 1px solid #e4e7ed;
  }
  .el-dialog__body {
    padding: 15px;
  }
  .dialog-footer{
    padding-right: 15px;
  }
  .recharge-card-header {
    background-color: var(--el-color-primary-light-9);
  }
  .el-input-number .el-input__inner {
    text-align: left;
  }
  .admin-customer-order-expand {
    background-color: #f3f3f4;
    padding: 10px 80px 10px 100px;
  }
  .admin-customer-order-expand.select-table {
    width: 100%;
    padding-top: 10px;
    padding-bottom: 23px;
  }
</style>
